﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ncp.Business;
using ncp.Business.Common;

namespace ncp.Web.page
{
    public partial class productlist : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof (productlist));

        }

        //获取地区信息
        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string GetArea(int type, string pId)
        {
            Dictionary<string, object> jsonResult = new Dictionary<string, object>();
            StringBuilder builder = new StringBuilder();

            try
            {
                var dt = ProductInfoBll.GetAreaList(type, pId, CommonConst.DB_Name);
                string value = "provinceID", text = "province";
                switch (type)
                {
                    case 0:
                        value = "provinceID";
                        text = "province";
                        builder.Append("<option value=\"\">--所在省份--</option>");
                        break;
                    case 1:
                        value = "cityID";
                        text = "city";
                        builder.Append("<option value=\"\">--所在地区--</option>");
                        break;
                    case 2:
                        value = "areaID";
                        text = "area";
                        builder.Append("<option value=\"\">--所在城市--</option>");
                        break;
                }
                if (dt != null)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        builder.AppendFormat("<option value=\"{0}\">{1}</option>", row[value], row[text]);
                    }
                }
                jsonResult.Add("isreload", true);
                jsonResult.Add("msg", builder.ToString());
            }
            catch (Exception ex)
            {
                jsonResult.Clear();
                jsonResult.Add("isreload", false);
                jsonResult.Add("msg", ex.Message);
            }

            return "[" + JsonHelper.ObjectToJSON(jsonResult) + "]";
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string GetProductList(int pageIndex, int pageSize, string json)
        {
            Dictionary<string, object> jsonResult = new Dictionary<string, object>();
            var dicProj = JsonHelper.JSONToObject<Dictionary<string, object>>(json);
            try
            {
                string more = GetMoreString(dicProj,false);
                if (more != "")
                {
                    dicProj.Add("more", more);
                }
                string orderby ="case when Vip_EndDate is null or Vip_EndDate<getdate() then '1900-1-1' end,User_Points, Product_StartTime desc";
                var dataTable = ProductInfoBll.GetProductInfoTable(pageIndex, pageSize, "*", orderby, dicProj,CommonConst.DB_Name);
                StringBuilder builder = new StringBuilder();
                
                if (dataTable.Rows.Count==0)
                {
                    builder.Append(
                        "<table style=\"border:none;width:100%\"><tr><td style=\"text-align:center;height:40px;\">没有找到相关产品！</td></tr></table>");
                }
                else
                {
                    int i = 0;
                    foreach (DataRow row in dataTable.Rows)
                    {
                        string style = i % 2 == 0 ? "cleftbrbs" : "cleftbrls";
                        string productId = EncryptHelper.EncryptString(row["Product_Id"].ToString());
                        builder.AppendFormat("<div class=\"bh-zzg-ny-{0}\"><dl class=\"bh-fl\"><dt class=\"bh-fl\">", style);
                        builder.AppendFormat("<a target=\"_blank\" href=\"/member/product/{0}.html\"><img src=\"{1}\"></a> </dt>",
                                             productId,
                                             (row["Product_Picture"].ToString() == "undefined" ? "/image/private/pic-12.jpg" : row["Product_Picture"]));
                        builder.AppendFormat("<dd class=\"bh-fr\"><h3>{0}</h3></dd><dd class=\"bh-fr\">",
                                             CommonBll.CutString(row["Product_Title"].ToString(),40,true));
                        builder.AppendFormat(
                            "<p>[产地:{0}&nbsp;&nbsp{1}&nbsp;{2}]&nbsp;[{3}]</p>",
                            row["province"], row["city"], row["area"],
                            Convert.ToDateTime(row["Product_StartTime"]).ToString("yyyy-MM-dd HH:mm"));
                        builder.AppendFormat(
                            "</dd><dd class=\"bh-fr\"><p>{0}</p></dd><dd class=\"bh-zzg-ny-cleftbrp bh-fr\"><p>企业：{1}</p></dd><div class=\"bh-clear\"></dl>",
                            CommonBll.CutString(CommonBll.NoHtml(row["Product_Remark"].ToString()), 100, true), row["Client_Name"]);

                        builder.Append("<ul class=\"bh-fr\">");
                        builder.AppendFormat("<li><img src=\"/image/bh-zzg-lyzx.jpg\" /><a href=\"javascript:void(0);\" onclick=\"onLeaveMessage('{0}')\">留言咨询</a></li>", CommonBll.BuildShopId(Convert.ToInt32(row["Client_Id"].ToString())));
                        if (row["User_QQ"] != DBNull.Value && row["User_QQ"].ToString()!="")
                        {
                            builder.Append("<li>");
                            builder.AppendFormat("<a target=\"_blank\" href=\"http://wpa.qq.com/msgrd?v=3&uin={0}&site=qq&menu=yes\">",row["User_QQ"]);
                            builder.AppendFormat("<img style=\"margin-left: 10px;\" border=\"0\" src=\"http://wpa.qq.com/pa?p=2:{0}:41\" alt=\"点击这里给我发消息\" title=\"点击这里给我发消息\"></a>", row["User_QQ"]);
                            builder.Append("</li>");
                        }
                        builder.AppendFormat("<li><img src=\"/image/bh-zzg-lxfs.jpg\" /><a href=\"javascript:void(0);\" class=\"cliContact\" userId=\"{0}\">联系方式</a></li>", CommonBll.BuildShopId(Convert.ToInt32(row["Client_Id"].ToString())));
                        builder.Append("</ul>");

                        builder.Append("<div class=\"bh-clear\"></div></div>");
                        i++;
                    }
                }
                jsonResult.Add("isreload", true);
                jsonResult.Add("msg", builder.ToString());
            }
            catch (Exception ex)
            {
                jsonResult.Clear();
                jsonResult.Add("isreload", false);
                jsonResult.Add("msg", ex.Message);
            }

            return "[" + JsonHelper.ObjectToJSON(jsonResult) + "]";
        }

        public string GetMoreString(Dictionary<string, object> dicProj,bool rec)
        {
            StringBuilder more = new StringBuilder();
            more.Append(" 1=1 ");
            if (!rec)
            {
                if (dicProj.ContainsKey("timeLimit"))
                {
                    string timeControl = dicProj["timeLimit"].ToString();
                    dicProj.Remove("timeLimit");
                    more.AppendFormat(" and datediff(day,Product_StartTime,getdate()) <{0}", timeControl);
                }
                string key = dicProj["key"].ToString();
                dicProj.Remove("key");
                if (key != "")
                {
                    key = Server.UrlDecode(key.Substring(1));
                    more.AppendFormat(" and Product_Title like '%{0}%' ", key);
                }
            }
            dicProj.Remove("key");
            dicProj.Remove("timeLimit");
            if (dicProj.ContainsKey("type"))
            {
                var type = dicProj["type"];
                dicProj.Remove("type");
                more.AppendFormat(" and G_Id={0}", type);
            }
            if (dicProj.ContainsKey("pclass"))
            {
                var pclass = dicProj["pclass"];
                dicProj.Remove("pclass");
                more.AppendFormat(" and GC_Id={0}", pclass);
            }
            if (dicProj.ContainsKey("channel"))
            {
                var channel = dicProj["channel"];
                dicProj.Remove("channel");
                more.AppendFormat(" and GC_Id in(select GC_Id from bi_GoodsClass where GC_PId={0})", channel);
            }
            if (dicProj.ContainsKey("cate"))
            {
                var cate = dicProj["cate"];
                dicProj.Remove("cate");
                more.AppendFormat(" and GC_Id in(select GC_Id from bi_GoodsClass where GC_PId in(select GC_Id from bi_GoodsClass where GC_PId= {0}))", cate);
            }
            return more.ToString();
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string GetProductCount(string json)
        {
            Dictionary<string, object> jsonResult = new Dictionary<string, object>();
            var dicProj = JsonHelper.JSONToObject<Dictionary<string, object>>(json);
            try
            {
                string more = GetMoreString(dicProj,false);
                if (more != "")
                {
                    dicProj.Add("more", more);
                }
                var count = ProductInfoBll.GetProductInfoCount(dicProj, CommonConst.DB_Name);
                jsonResult.Add("isreload", true);
                jsonResult.Add("msg", count);
            }
            catch (Exception ex)
            {
                jsonResult.Clear();
                jsonResult.Add("isreload", false);
                jsonResult.Add("msg", ex.Message);
            }
            return "[" + JsonHelper.ObjectToJSON(jsonResult) + "]";
        }

        //推荐
        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string GetRecProduct(string json)
        {
            Dictionary<string, object> jsonResult = new Dictionary<string, object>();
            try
            {
                var dicProj = JsonHelper.JSONToObject<Dictionary<string, object>>(json);
                StringBuilder more=new StringBuilder();
                more.Append(GetMoreString(dicProj,true));
                more.Append(" and CHARINDEX('c',Product_Flag)<>0");
                dicProj.Add("more",more);
                var dataTable = ProductInfoBll.GetProductInfoTable("top 20 *",dicProj,"",CommonConst.DB_Name,false);
                StringBuilder builder=new StringBuilder();
                foreach (DataRow row in dataTable.Rows)
                {
                    builder.AppendFormat(
                        "<dl><dt><a target=\"_blankv\" href=\"/product/{0}.html\"><img src=\"{1}\" /></a></dt><dd><a href=\"/product/{0}.html\">{2}</a></dd></dl>",
                        EncryptHelper.EncryptString(row["Product_Id"].ToString()), row["Product_Picture"],
                        row["Product_Title"]);
                }
                builder.Append("<div class=\"bh-clear\"></div>");
                jsonResult.Add("isreload", true);
                jsonResult.Add("msg", builder.ToString());
            }
            catch (Exception ex)
            {
                jsonResult.Clear();
                jsonResult.Add("isreload", false);
                jsonResult.Add("msg", ex.Message);
            }
            return "[" + JsonHelper.ObjectToJSON(jsonResult) + "]";
        }

        //判断用户是否已经登录
        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public bool IsLogin()
        {
            var userInfo = WebMasterCookie.GetCookie();
            if (userInfo != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string UserLogin(string account, string pwd)
        {
            Dictionary<string, object> jsonResult = new Dictionary<string, object>();
            try
            {
                //判断用户是否已经登录
                var userInfo = WebMasterCookie.GetCookie();
                if (userInfo != null)
                {
                    jsonResult.Add("isreload", true);
                }
                else
                {
                    DataTable table = ClientInfoBll.ClientLogin(CommonBll.InputText(account, 50),
                                                                EncryptHelper.EncryptString(pwd),  CommonConst.DB_Name);
                    if (table.Rows.Count > 0)
                    {
                        //判断当天是否已经登录过
                        if (table.Rows[0]["LastLoginTime"] == DBNull.Value ||
                            (Convert.ToDateTime(table.Rows[0]["LastLoginTime"].ToString()) - DateTime.Now).Days != 0)
                        {
                            //登录时积分+5并更新等级
                            ClientInfoBll.UpdateClientPoints(table.Rows[0]["Client_Id"].ToString(), CommonConst.gLoginPoints, "+",  CommonConst.DB_Name);
                            //更新最后登录时间
                            ClientInfoBll.UpateLastLoginTime(table.Rows[0]["Client_Id"].ToString(),  CommonConst.DB_Name);
                        }

                        jsonResult.Add("isreload", true);
                        var info = new UserInfo
                        {
                            Email = table.Rows[0]["User_Email"] == DBNull.Value ? "" : table.Rows[0]["User_Email"].ToString(),
                            Id = table.Rows[0]["Client_Id"].ToString(),
                            RelName = table.Rows[0]["Client_Name"] == DBNull.Value ? "" : table.Rows[0]["Client_Name"].ToString(),
                            Status = table.Rows[0]["User_Status"].ToString(),
                            UName = table.Rows[0]["Client_Account"].ToString()
                        };
                        info.Computername = HttpContext.Current.Application["computername"].ToString();
                        info.Computerip = HttpContext.Current.Application["computerip"].ToString();
                        WebMasterCookie.AddCookie(info);

                        Dictionary<string, object> dicLoginLog = new Dictionary<string, object>();
                        dicLoginLog.Add("user_id", info.Id);
                        dicLoginLog.Add("computername", info.Computername);
                        dicLoginLog.Add("computerip", info.Computerip);
                        LogLoginBll.AddLoginLog(dicLoginLog, CommonConst.DB_Name);
                    }
                    else
                    {
                        jsonResult.Clear();
                        jsonResult.Add("isreload", false);
                        jsonResult.Add("msg", "用户名或密码错误！");
                    }
                }

            }
            catch (Exception ex)
            {
                jsonResult.Clear();
                jsonResult.Add("isreload", false);
                jsonResult.Add("msg", ex.Message);
            }
            return "[" + JsonHelper.ObjectToJSON(jsonResult) + "]";

        }

        [AjaxPro.AjaxMethod]
        public string OnSaveMessage(string json, string shop)
        {
            Dictionary<string, object> jsonResult = new Dictionary<string, object>();
            if (CommonBll.IsLegitimateShopId(shop))
            {
                try
                {
                    var dicProj = JsonHelper.JSONToObject<Dictionary<string, object>>(json);
                    dicProj.Add("Client_Id", CommonBll.GetTheRealId(shop));
                    var content = Server.HtmlEncode(dicProj["Message_Note"].ToString()).Replace("/", "");
                    dicProj.Remove("Message_Note");
                    dicProj.Add("Message_Note", content);
                    var userInfo = WebMasterCookie.GetCookie();
                    if (userInfo != null)
                    {
                        dicProj.Add("Senter_Id", userInfo.Id);

                        dicProj.Add("Message_Date", DateTime.Now);
                        MessageInfoBll.InsertMessageInfo(dicProj, CommonConst.DB_Name);
                        jsonResult.Add("isreload", true);
                        jsonResult.Add("msg", "留言成功！");
                    }
                    else
                    {
                        jsonResult.Add("isreload", false);
                        jsonResult.Add("msg", "请登录后留言！");
                    }
                }
                catch (Exception ex)
                {
                    jsonResult.Clear();
                    jsonResult.Add("isreload", false);
                    jsonResult.Add("msg", ex.Message);
                }


            }
            else
            {
                jsonResult.Add("isreload", false);
                jsonResult.Add("msg", "0");
            }
            return "[" + JsonHelper.ObjectToJSON(jsonResult) + "]";
        }

        //验证验证码是否正确
        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string VerificationCode(string code)
        {
            Dictionary<string, object> jsonResult = new Dictionary<string, object>();
            string verCode = Session["VerificationCode"] == null ? "" : Session["VerificationCode"].ToString();
            if (verCode.ToLower() == code.ToLower())
            {
                jsonResult.Add("isreload", true);
            }
            else
            {
                jsonResult.Add("isreload", false);
            }
            return "[" + JsonHelper.ObjectToJSON(jsonResult) + "]";
        }

        //获取用户联系方式
        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string GetContact(string shop)
        {
            Dictionary<string, object> jsonResult = new Dictionary<string, object>();
            long shopId = 0;
            if (long.TryParse(shop, out shopId) && shopId > 103264587)
            {
                var dt = ClientInfoBll.GetClientById((shopId - 103264587).ToString(), CommonConst.DB_Name);
                if (dt.Rows.Count != 0)
                {
                    jsonResult.Add("isreload", true);
                    StringBuilder builder = new StringBuilder();
                    builder.Append("<ul style=\"padding:10px;\" class=\"bh-uli-yy\">");
                    if (dt.Rows[0]["User_CellPhone"].ToString() != "")
                    {
                        builder.AppendFormat("<li><span>移动电话：</span> {0}</li>", dt.Rows[0]["User_CellPhone"]);
                    }
                    if (dt.Rows[0]["User_TelPhone"].ToString() != "")
                    {
                        builder.AppendFormat("<li><span>固定电话：</span> {0}</li>", dt.Rows[0]["User_TelPhone"]);
                    }
                    if (dt.Rows[0]["User_Email"].ToString() != "")
                    {
                        builder.AppendFormat("<li><span>电子邮箱：</span> {0}</li>", dt.Rows[0]["User_Email"]);
                    }
                    if (dt.Rows[0]["User_Contact"].ToString() != "")
                    {
                        builder.AppendFormat("<li><span>联系人：</span> {0}</li>", dt.Rows[0]["User_Contact"]);
                    }
                    if (dt.Rows[0]["User_Url"].ToString() != "")
                    {
                        builder.AppendFormat("<li><span>公司网址：</span> {0}</li>", dt.Rows[0]["User_Url"]);
                    }
                    if (dt.Rows[0]["User_Address"].ToString() != "")
                    {
                        builder.AppendFormat("<li><span>公司地址：</span> {0}</li>", dt.Rows[0]["User_Address"]);
                    }
                    builder.Append("</ul>");
                    jsonResult.Add("msg", builder.ToString());
                }
                else
                {
                    jsonResult.Add("isreload", false);
                    jsonResult.Add("msg", "0");
                }
            }
            else
            {
                jsonResult.Add("isreload", false);
                jsonResult.Add("msg", "0");
            }
            return "[" + JsonHelper.ObjectToJSON(jsonResult) + "]";
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public void InsertKey(string key)
        {
            string ip = HttpContext.Current.Application["Computerip"].ToString();
            ProductInfoBll.InsertSearchKey(Server.UrlDecode(key.Substring(1)),ip,0 , CommonConst.DB_Name);
        }
    }
}